﻿using Communication.Interface;
using Communication.Model.displacement;
using Communication.Model.netPacket;
using Communication.Model.packetType;
using Communication.TcpIpService.tcpAsynService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Communication.TcpIpService
{
    public class CommunicationService : ICommunicationService
    {
        //界面刷新线程
        private NetPacket _netPacket = null;
        private bool autoRefreshFlag = false;
        public Task refreshTask;

        private Socket _clientSocket = null;
        private TcpAsynService _tcpAsynService = null;
        private string _serverIP { get; set; } = "192.168.2.64";
        private int _serverPort = 3000;
        private DateTime? _timeNetPacket = null;

        private Action<NetPacket> _dataReceived = null;

        public CommunicationService()
        {

        }
        public void AddDataHandler(Action<NetPacket> dataReceived)
        {
            _dataReceived -= dataReceived;
            _dataReceived += dataReceived;
        }

        public bool Connect2Server(string IP, int port)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.Connect(new IPEndPoint(IPAddress.Parse(IP), port)); //配置服务器IP与端口   
                                                                                  //_clientSocket =Connect2Server(serverIP, port);
                if (_clientSocket.Connected)
                {
                    //启动异步网络服务
                    NetworkStream netStream = new NetworkStream(_clientSocket);

                    if (_tcpAsynService != null)
                    {
                        _tcpAsynService = null;
                        Thread.Sleep(10);
                    }
                    _tcpAsynService = new TcpAsynService(netStream);
                    //开始接收数据
                    _tcpAsynService.ReceivePacket();
                    _tcpAsynService.SendText("run");
                    _tcpAsynService.SendText("startData");
                    //在AsynService类中处理接收到的数据，包括反序列化、提取包头、包体
                    //cp.AsynService.OnReceiveMsg += update;
                    _tcpAsynService.OnReceivedPacket -= DataMonitor;
                    _tcpAsynService.OnReceivedPacket += DataMonitor;
                    //cp.AsynService.ReceivePacket();
                    //初始化数据时间
                    _timeNetPacket = DateTime.Now;

                    //AsynService类接收到一个完整数据包后，触发事件OnReceive
                    //但是由于结构体的动态配置，服务类需要首先判断能否解析数据
                    //AsynService.OnReceivedPacket+=
                    return true;
                }
                Console.WriteLine(DateTime.Now.ToString() + "连接服务器失败");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString() + "连接服务器发生异常--");
                return false;
            }
        }

        public void Dispose()
        {
            if (_clientSocket != null)
            {
                _clientSocket.Close();
                _clientSocket.Dispose();
            }
            if (_tcpAsynService != null)
            {

            }
        }

        public bool GetConnectionStatus()
        {
            if (_timeNetPacket != null)
            {
                TimeSpan? span = DateTime.Now - _timeNetPacket;
                if (span?.TotalSeconds > 120)
                {
                    return false;
                }
            }
            return true;
        }

        public bool StartData()
        {
            _tcpAsynService.SendText("startData");
            return true;
        }

        public bool StopData()
        {
            _tcpAsynService.SendText("stopData");
            return true;
        }

        private void DataMonitor(NetPacket packet)
        {
            _dataReceived.Invoke(packet);
            //缓存最新的数据包
            _netPacket = packet;
        }

        public void EnableAutoRefresh()
        {
            autoRefreshFlag = true;
            refreshTask = Task.Run(() =>
             {
                 while (autoRefreshFlag)
                 {
                     if (_netPacket != null)
                         _dataReceived.Invoke(_netPacket);
                     Thread.Sleep(5000);
                 }
             });
        }

        public async void DisableAutoRefresh()
        {
            await Task.Run(() =>
            {
                autoRefreshFlag = false;
                refreshTask.Wait();
            });
        }

        public bool DebugMode()
        {
            _tcpAsynService.SendText("debug");

            return true;
        }

        public bool RunMode()
        {
            _tcpAsynService.SendText("run");

            return true;
        }

        //public void SetRunningMode(RunningMode mode)
        //{
        //    throw new NotImplementedException();
        //}
    }
}
